package com.example.nio.filelock;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Date;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年08月06日 15:55:00
 * @Description
 */
public class Demo06 {

    public static void main(String[] args) throws IOException, InterruptedException {
        RandomAccessFile f = new RandomAccessFile("test.txt", "rw");
        FileChannel channel = f.getChannel();
        System.out.println(new Date() + " 正在尝试获取文件锁...");

        FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
        System.out.println(new Date() + " 已获取到文件锁！");
        Thread.sleep(5000);   //假设要处理5秒钟
        System.out.println(new Date() + " 操作完毕，释放文件锁！");

        lock.release();
    }


}
